﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using Microsoft.Xna.Framework.Audio;

namespace PetRock
{
    public partial class GamePage : PhoneApplicationPage
    {
        ContentManager contentManager;
        GameTimer timer;
        SpriteBatch spriteBatch;
        SpriteFont spriteFont;

        private Texture2D rockTexture;
        private string currentPhrase;
        private TimeSpan timeToClearText;
        private double timeInterval;
        private int previousMessage;
        private FaceAndName faceAndName;

        private SoundEffect soundEffect1;
        private SoundEffect soundEffect2;
        private SoundEffect soundEffect3;
        private SoundEffectInstance soundEffect;

        private Random randomSound;

        // For rendering the XAML onto a texture
        UIElementRenderer elementRenderer;

        public GamePage()
        {
            InitializeComponent();

            // Get the content manager from the application
            contentManager = (Application.Current as App).Content;

            // Create a timer for this page
            timer = new GameTimer();
            timer.UpdateInterval = TimeSpan.FromTicks(333333);
            timer.Update += OnUpdate;
            timer.Draw += OnDraw;

            randomSound = new Random();

            // Use the LayoutUpdate event to know when the page layout 
            // has completed so that we can create the UIElementRenderer.
            LayoutUpdated += new EventHandler(GamePage_LayoutUpdated);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // Set the sharing mode of the graphics device to turn on XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true);

            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(SharedGraphicsDeviceManager.Current.GraphicsDevice);

            // TODO: use this.content to load your game content here
            rockTexture = contentManager.Load<Texture2D>("rockImage");
            currentPhrase = "";
            timeInterval = 5;
            timeToClearText = TimeSpan.FromSeconds(timeInterval);

            if (spriteFont == null)
                spriteFont = contentManager.Load<SpriteFont>("Andy");

            if (faceAndName == null)
                faceAndName = new FaceAndName(spriteFont, new Vector2(0, 0));

            soundEffect1 = contentManager.Load<SoundEffect>("CuteHey_1");
            soundEffect2 = contentManager.Load<SoundEffect>("CuteSqueal_1");
            soundEffect3 = contentManager.Load<SoundEffect>("CuteSqueal_2");

            previousMessage = 0;

            // Start the timer
            timer.Start();

            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            // Stop the timer
            timer.Stop();

            // Set the sharing mode of the graphics device to turn off XNA rendering
            SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(false);

            base.OnNavigatedFrom(e);
        }

        /// <summary>
        /// Allows the page to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        private void OnUpdate(object sender, GameTimerEventArgs e)
        {
            faceAndName.Update();
            TouchCollection touchCollection = TouchPanel.GetState();
            if (touchCollection.Count > 0 && timeToClearText <= TimeSpan.FromSeconds(timeInterval - 1))
            {
                timeToClearText = TimeSpan.FromSeconds(timeInterval);
                currentPhrase = generatePhrase();
                System.Diagnostics.Debug.WriteLine("Printed");

                int nextSound = randomSound.Next(3);
                if (nextSound == 0)
                    soundEffect1.Play();
                else if (nextSound == 1)
                    soundEffect2.Play();
                else
                    soundEffect3.Play();
                
            }

            if (timeToClearText <= TimeSpan.Zero)
            {
                currentPhrase = "";
            }
            else
            {
                timeToClearText -= e.ElapsedTime;
            }
        }

        /// <summary>
        /// Allows the page to draw itself.
        /// </summary>
        private void OnDraw(object sender, GameTimerEventArgs e)
        {
            SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Color.LightBlue);

            // Render the Silverlight controls using the UIElementRenderer.
            elementRenderer.Render();

            // TODO: Add your drawing code here
            spriteBatch.Begin();

            spriteBatch.DrawString(spriteFont, currentPhrase, new Vector2((SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2) - (spriteFont.MeasureString(currentPhrase).X / 2), 500), Color.Black);
            spriteBatch.Draw(rockTexture, new Vector2((SharedGraphicsDeviceManager.Current.GraphicsDevice.Viewport.Width / 2) - rockTexture.Width / 2, 225), Color.White);

            faceAndName.Draw(spriteBatch);

            // Using the texture from the UIElementRenderer, 
            // draw the Silverlight controls to the screen.
            spriteBatch.Draw(elementRenderer.Texture, Vector2.Zero, Color.White);

            spriteBatch.End();
        }

        private string generatePhrase()
        {
            Random rand = new Random();
            int randNum = rand.Next(12);
            while (randNum == previousMessage)
            {
                randNum = rand.Next(12);
            }

            previousMessage = randNum;

            if (randNum == 0)
            {
                faceAndName.setFace(":)");
                return "How are you?";
            }
            else if (randNum == 1)
            {
                faceAndName.setFace("<3");
                return "I love you!";
            }
            else if (randNum == 2)
            {
                faceAndName.setFace(";)");
                return "I'm bored. Want to \ndo something?";
            }
            else if (randNum == 3)
            {
                faceAndName.setFace(":>");
                return "What's up?";
            }
            else if (randNum == 4)
            {
                faceAndName.setFace("B)");
                return "Check out my shades!";
            }
            else if (randNum == 5)
            {
                faceAndName.setFace(">:)");
                return "Rock on!";
            }
            else if(randNum == 6)
            {
                faceAndName.setFace(":P");
                return "Why the long face?";
            }
            else if(randNum == 7)
            {
                faceAndName.setFace(":X");
                return "You can tell me anything. \nMy lips are sealed!";
            }
            else if(randNum == 8)
            {
                faceAndName.setFace("O:)");
                return "What? I didn't do anything.";
            }
            else if(randNum == 9)
            {
                faceAndName.setFace(":D");
                return "I just got a great idea! \nWant to hear it?";
            }
            else if(randNum == 10)
            {
                faceAndName.setFace("XD");
                return "HAHAHAHAHA!";
            }
            else
            {
                faceAndName.setFace(":]");
                return "Hello!";
            }
        }

        void GamePage_LayoutUpdated(object sender, EventArgs e)
        {
            // Create the UIElementRenderer to draw the XAML page to a texture.

            // Check for 0 because when we navigate away the LayoutUpdate event
            // is raised but ActualWidth and ActualHeight will be 0 in that case.
            if ((ActualWidth > 0) && (ActualHeight > 0))
            {
                SharedGraphicsDeviceManager.Current.PreferredBackBufferWidth = (int)ActualWidth;
                SharedGraphicsDeviceManager.Current.PreferredBackBufferHeight = (int)ActualHeight;
            }


            if (null == elementRenderer)
            {
                elementRenderer = new UIElementRenderer(this, (int)ActualWidth, (int)ActualHeight);
            }
        }
    }
}